package javaCode;

import java.awt.event.HierarchyBoundsAdapter;

import com.sun.org.apache.xerces.internal.impl.dv.ValidatedInfo;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;

public class LeetCode445 {
	 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	     int len1 = getLen(l1);
	     int len2 = getLen(l2);
	     ListNode head = null;
	     if(len1 > len2){
	    	 head = back(l1, l2,len1-len2);
	     }else{
	    	 head = back(l2, l1, len2 - len1);
	     }
	     if(head.val > 9){
	    	 ListNode temp = new ListNode(1);
	    	 head.val = head.val % 10;
	    	 temp.next = head;
	    	 head = temp;
	     }
		 return head;    
	 }
	 public int getLen(ListNode head){
		 ListNode p = head;
		 int count = 0;
		 while(p != null ){
			 count++;
			 p = p.next;
		 }
		 return count;
	 }
	 public ListNode  back(ListNode l1,ListNode l2,int offset) {
		 if(l1 == null){
			 return null;
		 }
		 ListNode result = null;
		 ListNode lastNode = null;
		 if(offset == 0){
				lastNode = back(l1.next, l2.next, 0);
		 }else {
				lastNode = back(l1.next, l2, offset-1);
		 }
		 
		 if(offset == 0){
			 result = new ListNode(l1.val + l2.val);
		 }else{
			 result = new ListNode(l1.val);
		 }
	
		
		 if(lastNode != null){
			if(lastNode.val > 9){
				result.val = result.val + 1;
				lastNode.val = lastNode.val % 10;
			}
			result.next = lastNode;
		 }
		return result;
	}
}
